<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { NButton, NPopconfirm, NSpace, NTag, NUpload, type UploadFileInfo, type UploadInst } from 'naive-ui';
import { fetchUnstructuredFileList, deleteUnstructuredFile, deleteUnstructuredFiles, uploadUnstructuredFile, uploadUnstructuredFiles, getUnstructuredFileDownloadUrl } from '@/service/api';
import { useLoading } from '@sa/hooks';
import { $t } from '@/locales';

const { loading, startLoading, endLoading } = useLoading(false);
const { bool: delLoading, setTrue: startDelLoading, setFalse: endDelLoading } = useLoading(false);

// 查询参数
const queryParams = reactive({
  fileName: '',
  fileType: '',
  uploadType: '',
  sourceType: '',
  pageNum: 1,
  pageSize: 10
});

// 表格数据
const tableData = ref<Api.Dataplatform.UnstructuredFile[]>([]);
const total = ref(0);

// 选中的行
const checkedRowKeys = ref<number[]>([]);

// 上传组件引用
const uploadRef = ref<UploadInst>();
const fileList = ref<UploadFileInfo[]>([]);

// 文件类型选项
const fileTypeOptions = [
  { label: '全部', value: '' },
  { label: 'PDF', value: 'PDF' },
  { label: 'Word', value: 'DOC' },
  { label: 'Excel', value: 'XLS' },
  { label: '图片', value: 'IMAGE' },
  { label: '视频', value: 'VIDEO' },
  { label: '其他', value: 'OTHER' }
];

// 上传类型选项
const uploadTypeOptions = [
  { label: '全部', value: '' },
  { label: '手动上传', value: 'MANUAL' },
  { label: '自动采集', value: 'AUTO' }
];

// 表格列配置
const columns = computed(() => [
  { type: 'selection', fixed: 'left' },
  { title: '文件名', key: 'fileName', width: 200, ellipsis: { tooltip: true } },
  {
    title: '文件类型',
    key: 'fileType',
    width: 100,
    render: (row: Api.Dataplatform.UnstructuredFile) => {
      const typeMap: Record<string, string> = {
        PDF: 'error',
        DOC: 'info',
        XLS: 'success',
        IMAGE: 'warning',
        VIDEO: 'default'
      };
      return h(NTag, { type: typeMap[row.fileType] || 'default' }, { default: () => row.fileType });
    }
  },
  { title: '文件大小', key: 'fileSizeFormatted', width: 120 },
  {
    title: '上传类型',
    key: 'uploadType',
    width: 100,
    render: (row: Api.Dataplatform.UnstructuredFile) => {
      return h(
        NTag,
        { type: row.uploadType === 'MANUAL' ? 'info' : 'success' },
        { default: () => (row.uploadType === 'MANUAL' ? '手动上传' : '自动采集') }
      );
    }
  },
  { title: '来源类型', key: 'sourceType', width: 100 },
  { title: '创建时间', key: 'createTime', width: 180 },
  { title: '创建者', key: 'createBy', width: 120 },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    fixed: 'right',
    render: (row: Api.Dataplatform.UnstructuredFile) => {
      return h(
        NSpace,
        {},
        {
          default: () => [
            h(
              NButton,
              {
                size: 'small',
                type: 'primary',
                onClick: () => handleView(row)
              },
              { default: () => '查看' }
            ),
            h(
              NButton,
              {
                size: 'small',
                onClick: () => handleDownload(row)
              },
              { default: () => '下载' }
            ),
            h(
              NPopconfirm,
              {
                onPositiveClick: () => handleDelete(row.id)
              },
              {
                default: () => '确定删除该文件吗？',
                trigger: () =>
                  h(
                    NButton,
                    {
                      size: 'small',
                      type: 'error'
                    },
                    { default: () => '删除' }
                  )
              }
            )
          ]
        }
      );
    }
  }
]);

// 查询列表
async function getTableData() {
  startLoading();
  try {
    const { data } = await fetchUnstructuredFileList(queryParams);
    if (data) {
      tableData.value = data.rows;
      total.value = data.total;
    }
  } finally {
    endLoading();
  }
}

// 搜索
function handleQuery() {
  queryParams.pageNum = 1;
  getTableData();
}

// 重置
function handleReset() {
  Object.assign(queryParams, {
    fileName: '',
    fileType: '',
    uploadType: '',
    sourceType: '',
    pageNum: 1,
    pageSize: 10
  });
  getTableData();
}

// 上传前检查
function beforeUpload(data: { file: UploadFileInfo; fileList: UploadFileInfo[] }) {
  // 可以在这里添加文件类型和大小验证
  return true;
}

// 自定义上传
async function customRequest({ file, onFinish, onError }: any) {
  try {
    await uploadUnstructuredFile(file.file as File, {
      uploadType: 'MANUAL',
      remark: ''
    });
    onFinish();
    window.$message?.success('文件上传成功');
    getTableData();
  } catch (error) {
    onError();
    window.$message?.error('文件上传失败');
  }
}

// 批量上传
async function handleBatchUpload() {
  if (fileList.value.length === 0) {
    window.$message?.warning('请先选择文件');
    return;
  }

  try {
    const files = fileList.value.map(item => item.file as File);
    await uploadUnstructuredFiles(files, {
      uploadType: 'MANUAL',
      remark: ''
    });
    window.$message?.success('批量上传成功');
    fileList.value = [];
    getTableData();
  } catch (error) {
    window.$message?.error('批量上传失败');
  }
}

// 查看详情
function handleView(row: Api.Dataplatform.UnstructuredFile) {
  window.$dialog?.info({
    title: '文件详情',
    content: () => {
      return h('div', { class: 'space-y-2' }, [
        h('p', `文件名: ${row.fileName}`),
        h('p', `文件类型: ${row.fileType}`),
        h('p', `文件大小: ${row.fileSizeFormatted}`),
        h('p', `文件MD5: ${row.fileMd5}`),
        h('p', `上传类型: ${row.uploadType === 'MANUAL' ? '手动上传' : '自动采集'}`),
        h('p', `来源类型: ${row.sourceType || '-'}`),
        h('p', `创建时间: ${row.createTime}`),
        h('p', `创建者: ${row.createBy}`),
        h('p', `备注: ${row.remark || '-'}`)
      ]);
    },
    positiveText: '关闭'
  });
}

// 下载文件
async function handleDownload(row: Api.Dataplatform.UnstructuredFile) {
  try {
    const { data } = await getUnstructuredFileDownloadUrl(row.id);
    if (data) {
      window.open(data, '_blank');
    }
  } catch (error) {
    window.$message?.error('获取下载链接失败');
  }
}

// 删除
async function handleDelete(id: number) {
  startDelLoading();
  try {
    await deleteUnstructuredFile(id);
    window.$message?.success('删除成功');
    getTableData();
  } finally {
    endDelLoading();
  }
}

// 批量删除
async function handleBatchDelete() {
  if (checkedRowKeys.value.length === 0) {
    window.$message?.warning('请先选择要删除的文件');
    return;
  }

  window.$dialog?.warning({
    title: '确认删除',
    content: `确定删除选中的 ${checkedRowKeys.value.length} 个文件吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      startDelLoading();
      try {
        await deleteUnstructuredFiles(checkedRowKeys.value);
        window.$message?.success('批量删除成功');
        checkedRowKeys.value = [];
        getTableData();
      } finally {
        endDelLoading();
      }
    }
  });
}

// 分页改变
function handlePageChange(page: number) {
  queryParams.pageNum = page;
  getTableData();
}

// 每页数量改变
function handlePageSizeChange(pageSize: number) {
  queryParams.pageSize = pageSize;
  queryParams.pageNum = 1;
  getTableData();
}

// 初始化
getTableData();
</script>

<template>
  <div class="h-full flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard :title="$t('page.dataplatform.fileCollection.unstructured')" :bordered="false" class="sm:flex-1-hidden card-wrapper">
      <!-- 搜索表单 -->
      <template #header-extra>
        <NSpace>
          <NInput
            v-model:value="queryParams.fileName"
            placeholder="文件名"
            clearable
            @keyup.enter="handleQuery"
          />
          <NSelect
            v-model:value="queryParams.fileType"
            :options="fileTypeOptions"
            placeholder="文件类型"
            clearable
            style="width: 120px"
          />
          <NSelect
            v-model:value="queryParams.uploadType"
            :options="uploadTypeOptions"
            placeholder="上传类型"
            clearable
            style="width: 120px"
          />
          <NButton type="primary" @click="handleQuery">
            <icon-ic-round-search class="mr-4px text-20px" />
            搜索
          </NButton>
          <NButton @click="handleReset">
            <icon-ic-round-refresh class="mr-4px text-20px" />
            重置
          </NButton>
        </NSpace>
      </template>

      <!-- 工具栏 -->
      <div class="mb-12px flex-y-center justify-between">
        <NSpace>
          <NUpload
            ref="uploadRef"
            v-model:file-list="fileList"
            multiple
            :show-file-list="false"
            :custom-request="customRequest"
            :before-upload="beforeUpload"
          >
            <NButton type="primary">
              <icon-ic-round-upload class="mr-4px text-20px" />
              上传文件
            </NButton>
          </NUpload>
          <NButton
            type="error"
            :disabled="checkedRowKeys.length === 0"
            :loading="delLoading"
            @click="handleBatchDelete"
          >
            <icon-ic-round-delete class="mr-4px text-20px" />
            批量删除
          </NButton>
        </NSpace>
        <div v-if="fileList.length > 0" class="text-14px text-gray-500">
          已选择 {{ fileList.length }} 个文件
          <NButton text type="primary" @click="handleBatchUpload">
            批量上传
          </NButton>
          <NButton text type="error" @click="fileList = []">
            清空
          </NButton>
        </div>
      </div>

      <!-- 表格 -->
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :row-key="(row: Api.Dataplatform.UnstructuredFile) => row.id"
        :scroll-x="1200"
        class="sm:h-full"
      />

      <!-- 分页 -->
      <template #footer>
        <NPagination
          v-model:page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :item-count="total"
          :page-sizes="[10, 20, 30, 50]"
          show-size-picker
          @update:page="handlePageChange"
          @update:page-size="handlePageSizeChange"
        />
      </template>
    </NCard>
  </div>
</template>

<style scoped>
.card-wrapper {
  @apply h-full flex-col;
}
</style>
